/*!
 * Page: mall/pay/Pay
 * License: MIT
 * Created: 2019-08-27 10:46
 */

import { GlobalData } from '/store/state'
import { mallApi } from '/api/mall'
import { getServer, getAppId, onNews } from '/store/mutations'
import { getDomoUser } from '/store/actions'
import { $event } from '/utils'
import { checkUserisVip } from '/store/mutations'

// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
Page({
  data: {
    commodityId: '',
    orig: true,
    top: GlobalData.menuRect.top,
    height: GlobalData.menuRect.height,
    currencyName: GlobalData.currencyName,
    // 收货地址
    realname: '',
    phone: '',
    province: '',
    city: '',
    country: '',
    detail: '',
    score: 0,
    exchangeRate: 0.1,
    reMarks: '',
    userScore: 0,
    needScore: 0,
    userPrice: 0,
    payToast: false,
    paySuccess: true,
    list: [] as any[],
    /** 总原价 */
    countMarket: 0,
    /** 需支付的总价 */
    countPrice: 0,
    /** 总邮费 */
    countfreight: 0,
    submitLock: false,
  },
  async onLoad() {
    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    this.setData({
      list: lastpage.data.priceList,
    })
    const form = wx.getStorageSync('address')
    this.setData(form)
    this.getPrice()
    this.getuser()
  },
  onShow() {
    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    getDomoUser()
    this.getPosition()
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      exchangeRate: GlobalData.currency.settings['recharge-ratio'],
      currencyName: GlobalData.currencyName,
      top: GlobalData.menuRect.top,
      height: GlobalData.menuRect.height,
    })
  },
  chooseAddress() {
    const chooseAddress = () => {
      wx.chooseAddress({
        success: (res) => {
          const form = {
            realname: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            country: res.countyName,
            detail: res.detailInfo,
          }
          wx.setStorageSync('address', form)

          this.setData(form)
        },
      })
    }

    // 获取收货地址授权信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.address'] === false) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.address'] === false) {
                wx.showToast({ title: '请允许使用您的收货地址', icon: 'none' })
              } else {
                chooseAddress()
              }
            },
          })
          return
        }
      },
    })
    chooseAddress()
  },
  onInput(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      reMarks: e.detail.value,
    })
  },
  reduce(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    const {
      data: { list },
    } = this
    if (list[index].quantity < 2) {
      list[index].quantity = 1
      return
    } else {
      list[index].quantity -= 1
    }
    this.setData({
      list,
    })
    this.getPrice()
  },
  add(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    const {
      data: { list },
    } = this

    list[index].quantity += 1
    this.setData({
      list,
    })
    this.getPrice()
  },
  /** 计算金额 */
  getPrice() {
    const {
      data: { list },
    } = this
    let countMarket = 0
    let countfreight = 0
    let countPrice = 0
    list.map((i) => {
      countPrice += i.userPrice * i.quantity
      countMarket += i.commodity.market_price * i.quantity
      countfreight += i.commodity.freight ? i.commodity.freight : 0
    })

    this.setData({
      countMarket,
      countfreight,
      countPrice,
    })
  },
  getuser() {
    const user = wx.getStorageSync(`${getServer()}/logged`).data || []
    if (user.vip) {
      user.vip.isVip = checkUserisVip(user)
    }
    this.setData({
      user,
    })
  },
  async openConfirm() {
    const {
      data: { list, province },
    } = this
    if (!this.data.phone) {
      wx.showToast({ title: '请选择收货地址', icon: 'none' })
      return
    }
    for (const i of list) {
      if (i.commodity.remote_areas && i.commodity.remote_areas.includes(province.slice(0, 2))) {
        wx.showModal({
          title: '提示',
          content: `抱歉，商品'${i.commodity.title}'暂不支持发货到${province}`,
          showCancel: false,
          confirmText: '知道了',
        })
        return
      }
      if (i.commodity.order_min_qty && i.quantity < i.commodity.order_min_qty) {
        wx.showModal({
          title: '提示',
          content: `商品${i.commodity.title},至少选择${i.commodity.order_min_qty}袋`,
          showCancel: false,
          confirmText: '知道了',
        })
        return
      }
      if (i.commodity.order_max_qty && i.quantity > i.commodity.order_max_qty) {
        wx.showModal({
          title: '提示',
          content: `商品${i.commodity.title},最多选择${i.commodity.order_max_qty}袋`,
          showCancel: false,
          confirmText: '知道了',
        })
        return
      }
    }
    this.onSubmit()
  },
  async onSubmit() {
    try {
      await onNews(['{{MERCHANT_SHIPPING_KEY}}'])
    } catch (error) {
      wx.showToast({ title: '请配置正确的订阅消息key，具体位置在package.json', icon: 'none' })
    }
    const {
      data: { submitLock, list },
    } = this
    const commodities = [] as any[]
    if (submitLock) return
    this.setData({ submitLock: true })
    list.map((i) => {
      commodities.push({
        commodity_id: i.commodity.id,
        quantity: i.quantity,
        commodity_option: i.commodity_option,
      })
    })
    try {
      const payInfo = await mallApi.payCartsOrder({
        commodities,
        pay_method: 'WechatPay_Js',
        user_remark: this.data.reMarks,
        address: {
          name: this.data.realname,
          phone: this.data.phone,
          province: this.data.province,
          city: this.data.city,
          country: this.data.country,
          detail: this.data.detail,
        },
        openid: wx.getStorageSync(`${getServer()}/openId`).data,
        appid: getAppId() ? getAppId() : '{{APP_ID}}',
      })
      if (payInfo.message) {
        this.payShowToast(true)
        return
      }
      wx.requestPayment({
        ...payInfo,
        success: () => {
          this.payShowToast(true)
        },
        fail: () => {
          this.payShowToast(false)
        },
      })
      this.setData({ submitLock: false })
    } catch (error) {
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
      this.setData({ submitLock: false })
    }
  },
  closeConfirm() {
    this.setData({ showConfirm: false })
  },
  payShowToast(success: boolean) {
    this.setData({
      payToast: true,
      paySuccess: success,
    })
    success && $event.emit('after:payCarts')
  },
  closePayShow() {
    this.setData({ payToast: false })
  },
  toHome() {
    wx.switchTab({
      url: '/pages/feed/list/list',
    })
  },
  toDetail(e: any) {
    const {
      currentTarget: {
        dataset: { commodityid },
      },
    } = e

    wx.navigateTo({
      url: `/mall/detail/detail?commodityId=${commodityid}`,
    })
  },
})
